//
//  DMFacebookManager.m
//  DualMediationSDK
//
//  Facebook功能管理器实现 - 重构版本
//  使用DMDelegate回调机制替代WDCallBack
//

#import "DMFacebookManager.h"
#import "DMFacebookTypes.h"
#import "DMSUCache.h"
#import <FBSDKCoreKit/FBSDKCoreKit.h>
#import <FBSDKLoginKit/FBSDKLoginKit.h>
#import <FBSDKShareKit/FBSDKShareKit.h>
#import "../../Utils/Logger/IMLogUtils.h"
#import "DMThinkingManager.h"
#import <FBAudienceNetwork/FBAudienceNetwork.h>

@interface DMFacebookManager()<FBSDKSharingDelegate>

@property (nonatomic, strong) FBSDKLoginManager *loginManager;

@end

@implementation DMFacebookManager

static DMFacebookManager *_sharedManager = nil;
static dispatch_once_t onceToken;

+ (instancetype)sharedManager {
    dispatch_once(&onceToken, ^{
        _sharedManager = [[self alloc] init];
    });
    return _sharedManager;
}

- (instancetype)init {
    self = [super init];
    if (self) {
        self.loginManager = [[FBSDKLoginManager alloc] init];
        
        // 监听Facebook登录状态变化
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(accessTokenDidChange:)
                                                     name:FBSDKAccessTokenDidChangeNotification
                                                   object:nil];
        
        // 监听Facebook用户档案变化
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(profileDidChange:)
                                                     name:FBSDKProfileDidChangeNotification
                                                   object:nil];
        
        [IMLogUtils info:IMLogTagAPI format:@"📘 DMFacebookManager 初始化完成"];
    }
    return self;
}

#pragma mark - 初始化和配置

+ (BOOL)initializeWithApplication:(UIApplication *)application launchOptions:(NSDictionary *)launchOptions {
    @try {
        BOOL result = [[FBSDKApplicationDelegate sharedInstance] application:application
                                                didFinishLaunchingWithOptions:launchOptions];
        [FBAdSettings setAdvertiserTrackingEnabled:YES];
        [[FBSDKSettings sharedSettings] enableLoggingBehavior:FBSDKLoggingBehaviorAppEvents];
        [IMLogUtils info:IMLogTagAPI format:@"📘 Facebook SDK 初始化%@", result ? @"成功" : @"失败"];
        
        return result;
    } @catch (NSException *exception) {
        [IMLogUtils error:IMLogTagError format:@"❌ Facebook SDK 初始化异常: %@", exception.reason];
        return NO;
    }
}

+ (BOOL)handleOpenURL:(UIApplication *)app url:(NSURL *)url options:(NSDictionary<UIApplicationOpenURLOptionsKey,id> *)options {
    BOOL result = [[FBSDKApplicationDelegate sharedInstance] application:app
                                                                  openURL:url
                                                                  options:options];
    
    [IMLogUtils info:IMLogTagAPI format:@"📘 处理URL回调: %@, 结果: %@", url.absoluteString, result ? @"成功" : @"失败"];
    
    return result;
}

#pragma mark - 登录功能

+ (void)login {
    @try {
        DMFacebookManager *manager = [DMFacebookManager sharedManager];
        
        // 检查是否已经有有效的访问令牌
        if ([FBSDKAccessToken currentAccessToken]) {
            [IMLogUtils info:IMLogTagAPI format:@"📘 用户已登录，直接返回用户信息"];
            
            // 获取用户信息
            [manager fetchUserInfo];
            return;
        }
        
        [IMLogUtils info:IMLogTagAPI format:@"📘 开始Facebook登录"];
        
        // 执行登录
        [manager.loginManager logInWithPermissions:@[@"public_profile", @"email"]
                                 fromViewController:nil
                                            handler:^(FBSDKLoginManagerLoginResult * _Nullable result, NSError * _Nullable error) {
            @try {
                if (error) {
                    [IMLogUtils error:IMLogTagError format:@"❌ Facebook登录失败: %@", error.localizedDescription];
                    
                    NSError *fbError = DMFacebookError(DMFacebookErrorCodeLoginFailed, error.localizedDescription);
                    [[DMLifecycleManager sharedManager] forwardFacebookLoginError:fbError];
                } else if (result.isCancelled) {
                    [IMLogUtils info:IMLogTagAPI format:@"❌ 用户取消Facebook登录"];
                    
                    [[DMLifecycleManager sharedManager] forwardFacebookLoginCancel];
                } else {
                    [IMLogUtils info:IMLogTagAPI format:@"✅ Facebook登录成功"];
                    
                    // 获取用户信息
                    [manager fetchUserInfo];
                }
            } @catch (NSException *exception) {
                [IMLogUtils error:IMLogTagError format:@"❌ Facebook登录回调异常: %@", exception.reason];
                
                NSError *fbError = DMFacebookError(DMFacebookErrorCodeLoginFailed, exception.reason);
                [[DMLifecycleManager sharedManager] forwardFacebookLoginError:fbError];
            }
        }];
    } @catch (NSException *exception) {
        [IMLogUtils error:IMLogTagError format:@"❌ Facebook登录异常: %@", exception.reason];
        
        NSError *fbError = DMFacebookError(DMFacebookErrorCodeLoginFailed, exception.reason);
        [[DMLifecycleManager sharedManager] forwardFacebookLoginError:fbError];
    }
}

+ (void)logout {
    DMFacebookManager *manager = [DMFacebookManager sharedManager];
    
    [IMLogUtils info:IMLogTagAPI format:@"📘 开始Facebook登出"];
    
    [manager.loginManager logOut];
    
    // 清除缓存的用户信息
    manager.cachedUserInfo = nil;
    
    [IMLogUtils info:IMLogTagAPI format:@"✅ Facebook登出完成"];
}

+ (BOOL)isLoggedIn {
    return [FBSDKAccessToken currentAccessToken] != nil;
}

+ (nullable NSString *)currentAccessToken {
    return [FBSDKAccessToken currentAccessToken].tokenString;
}

- (void)FBShareWithTitle:(NSString *)title url:(NSString *)url content:(NSString *)shareContent
{
    
    if (@available(iOS 13.0, *))
    {

    }
    else
    {
        [self sysShareFunctionWithTitle:title url:url];
    }
    
    
    
}

// 已弃用的系统分享方法，使用新的Facebook分享API替代
- (void)sysShareFunctionWithTitle:(NSString *)title url:(NSString *)url {
    [IMLogUtils warning:IMLogTagAPI format:@"⚠️ 使用已弃用的系统分享方法，建议使用新的Facebook分享API"];
    
    // 使用新的Facebook分享方法替代
    [self shareContentWithTitle:title url:url description:@""];
}

- (void)autoLoginWithToken:(FBSDKAccessToken *)token {
    
}

- (void)newLogin {
    [IMLogUtils info:IMLogTagAPI format:@"facebook login newLogin"];
    UIViewController *rootController = [[[UIApplication sharedApplication].windows objectAtIndex:0] rootViewController];
    FBSDKLoginManager *login = [[FBSDKLoginManager alloc] init];
//    [login logOut];
    [login logInWithPermissions:@[@"public_profile"] fromViewController:rootController handler:^(FBSDKLoginManagerLoginResult *_Nullable result, NSError *_Nullable error) {
        [self FBLoginCompleWithResult:result error:error];
    }];
}

- (void)FBLogOut
{
    NSInteger slot = 0;
    [DMSUCache deleteItemInSlot:slot];
    [FBSDKAccessToken setCurrentAccessToken:nil];
    [FBSDKProfile setCurrentProfile:nil];
    
    FBSDKLoginManager *login = [[FBSDKLoginManager alloc] init];
    [login logOut];
}

// 已弃用的登录完成方法，使用新的DMDelegate回调机制替代
- (void)FBLoginCompleWithResult:(FBSDKLoginManagerLoginResult *)result error:(NSError *)error {
    [IMLogUtils warning:IMLogTagAPI format:@"⚠️ 使用已弃用的登录完成方法，建议使用新的login方法"];
    
    if (error) {
        [IMLogUtils error:IMLogTagError format:@"❌ Facebook登录失败: %@", error.localizedDescription];
        
        NSError *fbError = DMFacebookError(DMFacebookErrorCodeLoginFailed, error.localizedDescription);
        [[DMLifecycleManager sharedManager] forwardFacebookLoginError:fbError];
    } else if (result.isCancelled) {
        [IMLogUtils info:IMLogTagAPI format:@"❌ 用户取消Facebook登录"];
        
        [[DMLifecycleManager sharedManager] forwardFacebookLoginCancel];
    } else {
        [IMLogUtils info:IMLogTagAPI format:@"✅ Facebook登录成功"];
        
        // 获取用户信息
        [self fetchUserInfo];
    }
}

#pragma mark - 用户信息

+ (void)getUserInfo {
    DMFacebookManager *manager = [DMFacebookManager sharedManager];
    [manager fetchUserInfo];
}

+ (nullable DMFacebookUserInfo *)getCachedUserInfo {
    return [DMFacebookManager sharedManager].cachedUserInfo;
}

- (void)fetchUserInfo {
    if (![FBSDKAccessToken currentAccessToken]) {
        [IMLogUtils error:IMLogTagError format:@"❌ 无有效访问令牌，无法获取用户信息"];
        
        NSError *error = DMFacebookError(DMFacebookErrorCodeNoAccessToken, @"无有效访问令牌");
        [[DMLifecycleManager sharedManager] forwardFacebookUserInfoError:error];
        return;
    }
    
    [IMLogUtils info:IMLogTagAPI format:@"📘 开始获取用户信息"];
    
    FBSDKGraphRequest *request = [[FBSDKGraphRequest alloc]
                                  initWithGraphPath:@"me"
                                  parameters:@{@"fields": @"id,name,email,picture.type(large)"}];
    
    [request startWithCompletion:^(id<FBSDKGraphRequestConnecting>  _Nullable connection, id  _Nullable result, NSError * _Nullable error) {
        if (error) {
            [IMLogUtils error:IMLogTagError format:@"❌ 获取用户信息失败: %@", error.localizedDescription];
            
            NSError *fbError = DMFacebookError(DMFacebookErrorCodeUserInfoFailed, error.localizedDescription);
            [[DMLifecycleManager sharedManager] forwardFacebookUserInfoError:fbError];
        } else {
            [IMLogUtils info:IMLogTagAPI format:@"✅ 获取用户信息成功: %@", result];
            
            // 创建用户信息对象
            DMFacebookUserInfo *userInfo = [[DMFacebookUserInfo alloc] init];
            userInfo.userId = result[@"id"];
            userInfo.name = result[@"name"];
            userInfo.email = result[@"email"];
            userInfo.pictureURL = result[@"picture"][@"data"][@"url"];
            
            // 缓存用户信息
            self.cachedUserInfo = userInfo;
            
            // 转换为字典格式
            NSDictionary *userInfoDict = [userInfo toDictionary];
            
            // 触发登录成功回调
            [[DMLifecycleManager sharedManager] forwardFacebookLoginSuccess:userInfoDict];
            
            // 触发用户信息获取成功回调
            [[DMLifecycleManager sharedManager] forwardFacebookUserInfoSuccess:userInfoDict];
        }
    }];
}

//获取用户信息 picture用户头像
- (void)getUserInfoWithResult:(NSString *)userID
{
    
}

#pragma mark - Notification

- (void)_updateContent:(NSNotification *)notification {
    FBSDKProfile *profile = notification.userInfo[FBSDKProfileChangeNewKey];
    [self labelDisplayWithProfile:profile];
}

- (void)_accessTokenChanged:(NSNotification *)notification
{
    FBSDKAccessToken *token = notification.userInfo[FBSDKAccessTokenChangeNewKey];
    if (!token) {
        [FBSDKAccessToken setCurrentAccessToken:nil];
        [FBSDKProfile setCurrentProfile:nil];
    } else {
        NSInteger slot = 0;
        DMSUCacheItem *item = [DMSUCache itemForSlot:slot] ?: [[DMSUCacheItem alloc] init];
        if (![item.token isEqualToAccessToken:token]) {
            item.token = token;
            [DMSUCache saveItem:item slot:slot];
        }
    }
}

- (void)labelDisplayWithProfile:(FBSDKProfile *)profile{
    NSInteger slot = 0;
    if (profile) {
        DMSUCacheItem *cacheItem = [DMSUCache itemForSlot:slot];
        cacheItem.profile = profile;
        [DMSUCache saveItem:cacheItem slot:slot];
        
    }
}

#pragma mark - 分享功能

+ (void)shareWithTitle:(NSString *)title url:(NSString *)url description:(NSString *)description {
    DMFacebookManager *manager = [DMFacebookManager sharedManager];
    [manager shareContentWithTitle:title url:url description:description];
}

+ (void)shareImage:(UIImage *)image {
    DMFacebookManager *manager = [DMFacebookManager sharedManager];
    [manager shareImageContent:image];
}

- (void)shareContentWithTitle:(NSString *)title url:(NSString *)url description:(NSString *)description {
    [IMLogUtils info:IMLogTagAPI format:@"📘 开始Facebook链接分享"];
    
    // 埋点：分享请求事件
    NSDictionary *shareProperties = @{
        @"w_share_type": @"link",
        @"w_share_platform": @"facebook",
        @"w_share_title": title ?: @"",
        @"w_share_url": url ?: @"",
        @"w_share_description": description ?: @""
    };
    [[DMThinkingManager sharedManager] thinkingTrackEventWithKey:@"SDK_share_request" properties:shareProperties];
    [IMLogUtils info:IMLogTagAPI format:@"📊 埋点事件: SDK_share_request, 平台: facebook, 类型: link"];
    
    FBSDKShareLinkContent *content = [[FBSDKShareLinkContent alloc] init];
    content.contentURL = [NSURL URLWithString:url];
    content.quote = description;
    
    [self showShareDialogWithContent:content];
}

- (void)shareImageContent:(UIImage *)image {
    [IMLogUtils info:IMLogTagAPI format:@"📘 开始Facebook图片分享"];
    
    // 埋点：分享请求事件
    NSDictionary *shareProperties = @{
        @"w_share_type": @"image",
        @"w_share_platform": @"facebook",
        @"w_image_size": [NSString stringWithFormat:@"%.0fx%.0f", image.size.width, image.size.height]
    };
    [[DMThinkingManager sharedManager] thinkingTrackEventWithKey:@"SDK_share_request" properties:shareProperties];
    [IMLogUtils info:IMLogTagAPI format:@"📊 埋点事件: SDK_share_request, 平台: facebook, 类型: image"];
    
    FBSDKSharePhoto *photo = [[FBSDKSharePhoto alloc] initWithImage:image isUserGenerated:YES];
    photo.image = image;
    photo.isUserGenerated = YES;
    
    FBSDKSharePhotoContent *content = [[FBSDKSharePhotoContent alloc] init];
    content.photos = @[photo];
    
    [self showShareDialogWithContent:content];
}

- (void)showShareDialogWithContent:(id<FBSDKSharingContent>)content {
    @try {
        if (!content) {
            [IMLogUtils error:IMLogTagError format:@"❌ 分享内容为空"];
            
            NSError *error = DMFacebookError(DMFacebookErrorCodeShareFailed, @"分享内容为空");
            [[DMLifecycleManager sharedManager] forwardFacebookShareComplete:NO message:@"分享内容为空"];
            return;
        }
        
        FBSDKShareDialog *dialog = [[FBSDKShareDialog alloc] initWithViewController:nil content:content delegate:self];
        
        if ([dialog canShow]) {
            [dialog show];
        } else {
            [IMLogUtils error:IMLogTagError format:@"❌ 无法显示分享对话框"];
            
            NSError *error = DMFacebookError(DMFacebookErrorCodeShareFailed, @"无法显示分享对话框");
            [[DMLifecycleManager sharedManager] forwardFacebookShareComplete:NO message:@"无法显示分享对话框"];
        }
    } @catch (NSException *exception) {
        [IMLogUtils error:IMLogTagError format:@"❌ 分享对话框异常: %@", exception.reason];
        
        NSError *error = DMFacebookError(DMFacebookErrorCodeShareFailed, exception.reason);
        [[DMLifecycleManager sharedManager] forwardFacebookShareComplete:NO message:exception.reason];
    }
}

#pragma mark - FBSDKSharingDelegate

- (void)sharer:(id<FBSDKSharing>)sharer didCompleteWithResults:(NSDictionary *)results {
    [IMLogUtils info:IMLogTagAPI format:@"✅ Facebook分享成功"];
    
    // 埋点：分享成功事件
    NSDictionary *shareProperties = @{
        @"w_share_platform": @"facebook",
        @"w_share_result": @"success",
        @"w_post_id": results[@"postId"] ?: @""
    };
    [[DMThinkingManager sharedManager] thinkingTrackEventWithKey:@"SDK_share_success" properties:shareProperties];
    [IMLogUtils info:IMLogTagAPI format:@"📊 埋点事件: SDK_share_success, 平台: facebook"];
    
    [[DMLifecycleManager sharedManager] forwardFacebookShareComplete:YES message:@"分享成功"];
    
    // 调用新的回调接口
    if (self.shareCallback) {
        DMFacebookShareResult *result = [[DMFacebookShareResult alloc] init];
        result.success = YES;
        result.shareId = results[@"postId"];
        result.shareTime = [NSDate date];
        
        self.shareCallback(result, nil);
        self.shareCallback = nil; // 清除回调
    }
}

- (void)sharer:(id<FBSDKSharing>)sharer didFailWithError:(NSError *)error {
    [IMLogUtils error:IMLogTagError format:@"❌ Facebook分享失败: %@", error.localizedDescription];
    
    // 埋点：分享失败事件
    NSDictionary *shareProperties = @{
        @"w_share_platform": @"facebook",
        @"w_share_result": @"fail",
        @"w_error_code": @(error.code),
        @"w_error_message": error.localizedDescription ?: @""
    };
    [[DMThinkingManager sharedManager] thinkingTrackEventWithKey:@"SDK_share_fail" properties:shareProperties];
    [IMLogUtils info:IMLogTagAPI format:@"📊 埋点事件: SDK_share_fail, 平台: facebook, 错误: %@", error.localizedDescription];
    
    NSError *fbError = DMFacebookError(DMFacebookErrorCodeShareFailed, error.localizedDescription);
    [[DMLifecycleManager sharedManager] forwardFacebookShareComplete:NO message:error.localizedDescription];
    
    // 调用新的回调接口
    if (self.shareCallback) {
        self.shareCallback(nil, fbError);
        self.shareCallback = nil; // 清除回调
    }
}

- (void)sharerDidCancel:(id<FBSDKSharing>)sharer {
    [IMLogUtils info:IMLogTagAPI format:@"❌ 用户取消Facebook分享"];
    
    // 埋点：分享取消事件
    NSDictionary *shareProperties = @{
        @"w_share_platform": @"facebook",
        @"w_share_result": @"cancel"
    };
    [[DMThinkingManager sharedManager] thinkingTrackEventWithKey:@"SDK_share_cancel" properties:shareProperties];
    [IMLogUtils info:IMLogTagAPI format:@"📊 埋点事件: SDK_share_cancel, 平台: facebook"];
    
    [[DMLifecycleManager sharedManager] forwardFacebookShareComplete:NO message:@"用户取消分享"];
    
    // 调用新的回调接口
    if (self.shareCallback) {
        NSError *fbError = DMFacebookError(DMFacebookErrorCodeShareCancelled, @"用户取消分享");
        self.shareCallback(nil, fbError);
        self.shareCallback = nil; // 清除回调
    }
}







@end
